local Msg = require("core.Msg")
local Util = require("common.Util")
local Lang  = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local AbsActLogic = require("absAct.AbsActLogic")
local AbsActDefine = require("absAct.AbsActDefine")
local MailManager = require("mail.MailManager")
local MailExcel = require("excel.mail")
local AbsActExcel = require("excel.absAct")
local ItemExcel = require("excel.item").item
local ItemDefine = require("bag.ItemDefine")
local YunYingLogic = require("yunying.YunYingLogic")
local PanelDefine = require("broadcast.PanelDefine")

--[[ 
    占卜轮盘 
    1.actID(活动ID)或开始时间不一样则把DB数据重置
    2.抽奖规则,每次抽奖获得是策划按顺序配置的固定奖励
    3.轮盘奖励全部抽完,不刷新.
    4.活动开启时间,占卜功能中的每次合成和刷新都会获得配置相对应的道具奖励
    5.活动结束后,剩余的抽奖道具全部转化为其它配置的道具,并通过邮件发送
        DB:
        human.db.absAct[id] = {
           startTime = xxx,     --占卜轮盘开始时间
           times = xxx,         --占卜轮盘抽奖次数 
        }
        local: 
            getActID()          --获取活动id
            recoveryItem()      --活动结束后回收道具
            getInitDB()         --初始DB数据
            recovery()          --0点后自动执行回收逻辑
            getDrawCnt()        --获得下次抽奖需要的道具数量
        public:
            getAndSendMsg()     --发送活动数据
            get()               --活动抽奖
            isRed()             --红点提醒
            isActive()          --激活状态
            isOpen()            --活动开启
            updateDaily()       --0点时回调
            onZhanbuRefresh()   --占卜功能刷新时回调
            onZhanbuCompose()   --占卜合成时回调
            getZhanbuComposeCnt()--占卜合成时可得到道具数量
--]]

local function getActID()
    local state, id = AbsActLogic.isStartedByType(human, AbsActDefine.ABS_ACT_TYPE_9)
    if not state then return end

    return id
end

local function recoveryItem(human, id)
    local absActConfig = AbsActExcel.absActivity[id]
    if not absActConfig then return end
    local zblpConfig = AbsActExcel.zhanbuLunpan[absActConfig.actId]
    if not zblpConfig then 
        zblpConfig = AbsActExcel.zhanbuLunpan[absActConfig.turns[1]]
        if not zblpConfig then return end
    end

    local cnt = BagLogic.getItemCnt(human, zblpConfig.itemID)
    if cnt > 0 then
        BagLogic.delItem(human, zblpConfig.itemID, cnt, "zhanbulunpan_recovery")

        local mailConfig = MailExcel.mail[zblpConfig.mailID]
        local title = mailConfig.title
        local senderName = mailConfig.senderName
        local content = mailConfig.content

        local itemName = ItemExcel[zblpConfig.recoveryItemId].name
        local itemCnt = math.ceil(cnt / zblpConfig.recoveryProb[1]) * zblpConfig.recoveryProb[2]
        local items = { {zblpConfig.recoveryItemId, itemCnt} }

        MailManager.add(MailManager.SYSTEM, human.db._id, title, Util.format(content, itemName), items, senderName)	
    end
end

local function getInitDB(human, id, isRecovery)
    if not id then
        id = getActID()
        if not id then return end
    end

    local ret, endTime, startTime = AbsActLogic.isStarted(human, id)
    if not ret then
        --活动已结束,回收道具
        if isRecovery then
            recoveryItem(human, id)
        end
        return
    else
        --活动重新开过,回收道具
        local actDB = human.db.absAct[id]
        if actDB then
            actDB.times = actDB.times or 0
        end
        --[[ 不判断开始时间是否相等了  有玩家出现过活动在也回收了， 
            注释掉后，但后面如果配成每期之间没有间隔或在下一期开始后再上线，会出现回收不掉的问题。
            解决方案思路是存actID,例actDB.actId = absActConfig.actId,后面有配置这种情这样解决。
        if actDB and actDB.startTime ~= startTime then
            actDB.startTime = startTime
            actDB.times = 0  
            if isRecovery then
                recoveryItem(human, id)
            end      
        end --]]
        return actDB
    end
end

local function recovery(human, activityID)
    getInitDB(human, activityID, true)
end

local function getDrawCnt(human, times, id)
    local absActConfig = AbsActExcel.absActivity[id]
    if not absActConfig then return end

    local zblpConfig = AbsActExcel.zhanbuLunpan[absActConfig.actId]
    return zblpConfig.itemCnts[times + 1] or zblpConfig.itemCnts[#zblpConfig.itemCnts]
end

local init
function getAndSendMsg(human, id)
    local actDB = getInitDB(human, id)
    if not actDB then return end

    local absActConfig = AbsActExcel.absActivity[id]
    if not absActConfig then return end

    local msgRet = Msg.gc.GC_ABS_ZHAN_BU_LUA_PAN_QUERY
    if not init then
        local zblpConfig = AbsActExcel.zhanbuLunpan[absActConfig.actId]
        Grid.makeItem(msgRet.needItem, zblpConfig.itemID, 1)
        local len = 0
        for _, rewardCf in ipairs(zblpConfig.itemRewards) do
            len = len + 1
            Grid.makeItem(msgRet.list[len], rewardCf[1], rewardCf[2])
        end
        msgRet.list[0] = len

        len = 0
        for _, order in ipairs(zblpConfig.itemRewardOrders) do
            len = len + 1
            msgRet.orderList[len] = order
        end
        msgRet.orderList[0] = len

        len = 0
        for _, cnt in ipairs(zblpConfig.composeItemRewardCnts) do
            len = len + 1
            Grid.makeItem(msgRet.composeItems[len], zblpConfig.itemID, cnt)
        end
        msgRet.composeItems[0] = len

        Grid.makeItem(msgRet.resershItem, zblpConfig.itemID, zblpConfig.refreshItemRewardCnt)
        Grid.makeItem(msgRet.recoveryItem, zblpConfig.recoveryItemId, 1)
        msgRet.recoveryProb = tostring(zblpConfig.recoveryProb[1]) .. ":" .. tostring(zblpConfig.recoveryProb[2]) 
        
        init = true
    end

    msgRet.times = actDB.times
    msgRet.itemCnt = getDrawCnt(human, actDB.times, id)
    Msg.send(msgRet, human.fd)
end

function get(human, id)
    local actDB = getInitDB(human, id)
    if not actDB then return end

    local absActConfig = AbsActExcel.absActivity[id]
    if not absActConfig then return end

    local zblpConfig = AbsActExcel.zhanbuLunpan[absActConfig.actId]
    local nextTimes = actDB.times + 1
    
    local nextOrder = zblpConfig.itemRewardOrders[nextTimes]
    if not nextOrder then 
        return Broadcast.sendErr(human, Lang.ABS_ZHANBU_LUNPAN_ERR)
    end

    local drawItemCf = zblpConfig.itemRewards[nextOrder]
    if not drawItemCf then 
        return Broadcast.sendErr(human, Lang.ABS_ZHANBU_LUNPAN_ERR)
    end

    local needItemCnt = getDrawCnt(human, actDB.times, id)
    if not BagLogic.checkItemCnt(human, zblpConfig.itemID, needItemCnt) then
		return
	end

    BagLogic.delItem(human, zblpConfig.itemID, needItemCnt, "zhanbulunpan_get")

    actDB.times = nextTimes
    BagLogic.addItem(human, drawItemCf[1], drawItemCf[2], "zhanbulunpan_get")

    local msgRet = Msg.gc.GC_ABS_ZHAN_BU_LUA_PAN_GET
    msgRet.times = nextTimes
    msgRet.itemCnt = getDrawCnt(human, actDB.times, id)
    Msg.send(msgRet, human.fd)

    YunYingLogic.updateIcon(YYInfo[id], human)
    YunYingLogic.sendGroupUpdate(YYInfo[id], human, PanelDefine.PANEL_ID_3308)
end

function isRed(human, YYInfo, absActConfig)
    local actDB = getInitDB(human, absActConfig.funcID)
    if not actDB then return end

    local zblpConfig = AbsActExcel.zhanbuLunpan[absActConfig.actId]
    local nextTimes = actDB.times + 1
    
    local nextOrder = zblpConfig.itemRewardOrders[nextTimes]
    if not nextOrder then 
        return
    end

    local drawItemCf = zblpConfig.itemRewards[nextOrder]
    if not drawItemCf then 
        return 
    end

    local needItemCnt = getDrawCnt(human, actDB.times, absActConfig.funcID)
    local zblpConfig = AbsActExcel.zhanbuLunpan[absActConfig.actId]
    if zblpConfig.itemID == ItemDefine.ITEM_ZUANSHI_ID then
        local sum = human.db.zuanshi
        if sum < needItemCnt then
            return
        end
    end

    if BagLogic.getItemCnt(human, zblpConfig.itemID) < needItemCnt then
        return
    end

    return true
end

function isActive(human, YYInfo, funcConfig)
    return not isOpen(human, YYInfo, funcConfig)
end

function isOpen(human, YYInfo, funcConfig)
    return AbsActLogic.isStarted(human, funcConfig.funcID)
end

function updateDaily(human, activityID)
    recovery(human, activityID)
end

function onZhanbuRefresh(human)
   local id = getActID()
   if not id then return end

   local absActConfig = AbsActExcel.absActivity[id]
   if not absActConfig then return end
   local zblpConfig = AbsActExcel.zhanbuLunpan[absActConfig.actId]
   if not zblpConfig then return end

   local ret = AbsActLogic.isStarted(human, id) 
   if ret then
      if zblpConfig.refreshItemRewardCnt <= 0 then return end
      BagLogic.addItem(human, zblpConfig.itemID, zblpConfig.refreshItemRewardCnt, "zhanbulunpan_get")  
   end
end

function onZhanbuCompose(human, grade)
    local itemID,cnt = getZhanbuComposeCnt(human, grade)
    if cnt <= 0 then return end

    BagLogic.addItem(human, itemID, cnt, "zhanbulunpan_get")
end

function getZhanbuComposeCnt(human, grade)
   local id = getActID()
   if not id then return 0,0 end

   local absActConfig = AbsActExcel.absActivity[id]
   if not absActConfig then return 0,0 end

   local zblpConfig = AbsActExcel.zhanbuLunpan[absActConfig.actId]
   if not zblpConfig then return 0,0 end

   local ret = AbsActLogic.isStarted(human, id) 
   return ret and zblpConfig.itemID,zblpConfig.composeItemRewardCnts[grade] or 0,0
end